//
//  ParticipantsViewController.m
//  LetsParty
//
//  Created by MLin on 15/9/15.
//  Copyright (c) 2015年 LetsPartyTeam. All rights reserved.
//

#import "MLParticipantsViewController.h"
#import "MLParticipantsCell.h"
#import "NSString+Extension.h"


static NSString *const kCellIdentify = @"kCellIdentify";
static NSTimeInterval const indicatorDuration = 0; // 网络请求指示器至少出现的时间


@interface MLParticipantsViewController ()<UITableViewDelegate,UITableViewDataSource,MLParticipantsCellDelegate>
{
    NSMutableArray *_dataSource;
    CGFloat _text_height; // 计算自定义header高度
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UILabel * partyTitle;
@property (nonatomic, strong) UIView * titleLine;
@property (nonatomic, strong) GmailLikeLoadingView *loadingView;


@end

@implementation MLParticipantsViewController

#pragma mark - init
-(void)initParticipantsAppearance{
    // navi返回键
    [self.leftNavButton setImage:[UIImage imageNamed:@"iconfont-zuojiantou"] forState:UIControlStateNormal];
    [self.leftNavButton addTarget:self action:@selector(respondsToleftNavButton) forControlEvents:UIControlEventTouchUpInside];
    [self.lineView setHidden:NO];
    
    // 标题
    self.bartitleLabel.text = @"参加人员联系方式";
    
    // 计算自定义标题高度
//    NSMutableString *tempStr = [NSMutableString stringWithString:@"「」"];
//    [tempStr insertString:_headerTitleStr atIndex:1];
//    _headerTitleStr = tempStr;
    
    _text_height = [_headerTitleStr sizeWithFont:[UIFont boldSystemFontOfSize:20 * DHFlexibleVerticalMutiplier()] maxSize:CGSizeMake(300 * DHFlexibleHorizontalMutiplier(), 400)].height;
    
    // 标题Label
    [self.view addSubview:self.partyTitle];
    
    // tableview
    [self.view addSubview:self.tableView];
    
    [self.view addSubview:self.titleLine];
}

-(void)initDataSourceThenAppearance{
    // 活动指示器
    [self.view addSubview:self.loadingView];
    [self.loadingView setHidden:NO];
    [self.loadingView startAnimating];

    __weak typeof(self) myVC = self;
    [CYYNetWorkManager partyParticipatorsListWithPartyObjectId:_partyObjectId sucess:^(NSArray *array) {
        
        _dataSource = [NSMutableArray arrayWithArray:array];
        
        // 如果有自己，就把自己移到数组的第一位
        if (_isParticipate) {
            // 遍历数组
            NSString *currentUserName = [[CYYNetWorkManager currentUserGet] objectForKey:@"name"];
            for (int i =0; i < _dataSource.count; i++) {
                NSString *dataSourceName = [_dataSource[i] objectForKey:@"name"];
                if ([currentUserName isEqualToString:dataSourceName]) {
                    [_dataSource insertObject:_dataSource[i] atIndex:0];
                    [_dataSource removeObjectAtIndex:i+1];
                    break;
                }
            }
        }
        
        // 请求完数据，隐藏活动指示器
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(indicatorDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [myVC.loadingView stopAnimating];
            [myVC.loadingView setHidden:YES];
        });
        
        [myVC initParticipantsAppearance];
        
    } fail:^(NSError *error) {
        // 请求完数据，隐藏活动指示器
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(indicatorDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [myVC.loadingView stopAnimating];
            [myVC.loadingView setHidden:YES];
        });
//        NSLog(@"%@",error);
    }];
}

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self initDataSourceThenAppearance];
}

#pragma mark - action
-(void)respondsToleftNavButton{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - private method
- (void)alterViewWithMessage:(NSString *)message{
    UIAlertController * alterViewController = [UIAlertController alertControllerWithTitle:@"呼叫" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alterViewController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        // dismiss
        [alterViewController dismissViewControllerAnimated:YES completion:nil];
    }]];
    [alterViewController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        // 拨打电话
        NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",message];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
        // dismiss
        [alterViewController dismissViewControllerAnimated:YES completion:nil];
    }]];
    [self.parentViewController presentViewController:alterViewController animated:YES
                                          completion:nil];
}

#pragma mark - private protocol
-(void)btnClickedEvent:(NSString *)phoneNumber{
    [self alterViewWithMessage:phoneNumber];
}


#pragma mark - <UITableViewDelegate,UITableViewDataSource>

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MLParticipantsCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentify];
    if (!cell) {
        cell = [[MLParticipantsCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kCellIdentify];
        cell.delegate = self;
    }
    
    if (indexPath.row == 0 && _isParticipate) {
        // 参与者有自己的情况
        cell.nameLabel.text = @"自己";
        [cell.phLabel setHidden:YES];
        [cell.phoneButton setHidden:YES];
        return cell;
    }
    
    // cell设置内容
    cell.nameLabel.text = [_dataSource[indexPath.row] objectForKey:@"name"];
    cell.phonenumberLabel.text = [_dataSource[indexPath.row] objectForKey:@"mobilePhoneNumber"];
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataSource.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50 * DHFlexibleVerticalMutiplier();
}

// 取消选中高亮
-(BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

#pragma mark - getter
// 活动指示器视图
-(GmailLikeLoadingView *)loadingView{
    if (!_loadingView) {
        _loadingView = [[GmailLikeLoadingView alloc]initWithFrame:CGRectMake(320*0.5 - 12, 568*0.5 - 12, 15, 15) adjustWidth:YES];
        [_loadingView setHidden:YES];
    }
    return _loadingView;
}

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.partyTitle.frame) + 10 *DHFlexibleVerticalMutiplier(), 320 * DHFlexibleHorizontalMutiplier() , (568 - 64)*DHFlexibleVerticalMutiplier() - _text_height ) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 120;
        [_tableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
    }
    return _tableView;
}

-(UILabel *)partyTitle{
    if (!_partyTitle) {
        _partyTitle = [[UILabel alloc]initWithFrame:CGRectMake(15 * DHFlexibleVerticalMutiplier(), 64 * DHFlexibleVerticalMutiplier(), 290 * DHFlexibleVerticalMutiplier(), _text_height + 20 * DHFlexibleVerticalMutiplier())];
        _partyTitle.text = _headerTitleStr;
        _partyTitle.font = [UIFont systemFontOfSize:17 * DHFlexibleHorizontalMutiplier()];
        [_partyTitle setTextColor:[UIColor blackColor]];
        _partyTitle.numberOfLines = 0;
        _partyTitle.backgroundColor = [UIColor clearColor];
    }
    return _partyTitle;
}

-(UIView *)titleLine{
    if (!_titleLine) {
        _titleLine = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.partyTitle.frame), CGRectGetWidth(self.view.frame), 0.5)];
        _titleLine.backgroundColor = [UIColor lightGrayColor];
    }
    return _titleLine;
}

@end
